package com.my.study.structures.stack;

/**
 * @author Carlos
 * @version 1.0
 * @Description 数组模拟栈结构
 * @date 2021/6/18 21:38
 **/
public class ArrayStack {

    /**
     * 栈的最大值
     */
    private int maxSize;

    /**
     * 栈顶
     */
    private int top = -1;

    /**
     * 数组，模拟栈
     */
    private int[] stack;

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }


    public boolean isFull() {
        return top == this.maxSize - 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    /**
     * 入栈
     *
     * @param element
     */
    public void push(int element) {
        if (isFull()) {
            System.out.println("栈已满");
            return;
        }
        stack[++top] = element;
    }

    /**
     * 出栈
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }

        return stack[top--];
    }

    public int peek() {
        return stack[top];
    }

    /**
     * 遍历
     * <p>
     * 从栈顶向下遍历
     */
    public void list() {
        if (isEmpty()) {
            System.out.println("栈为空");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }


    //======================扩展方法============================

    /**
     * 返回运算符优先级，优先级越高，返回值越大
     *
     * <p>
     *     暂时只有*、/、+、-四种符号
     * </p>
     *
     * @param oper
     * @return
     */
    public int priority(int oper) {
        if (oper == '*' || oper == '/') {
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    /**
     * 判断是否为运算符
     *
     * @param val
     * @return
     */
    public boolean isOper(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    /**
     * 计算
     *
     * @param num1
     * @param num2
     * @param oper
     * @return
     */
    public int cal(int num1, int num2, int oper) {
        int result = 0;
        switch (oper) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num2 - num1;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num2 / num1;
                break;
            default:
                break;
        }

        return result;
    }



}
